package com.mobileservice.autoreply.activity;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.mobileservice.autoreply.R;
import com.mobileservice.autoreply.base.BaseActivity;
import com.mobileservice.autoreply.common.constant.CommConstant;
import com.mobileservice.autoreply.data.database.DatabaseDefination.PhoneContactTable;
import com.mobileservice.autoreply.data.manager.PhoneContactManager;
import com.mobileservice.autoreply.ui.adapter.ContactItemAdapter;
import com.mobileservice.autoreply.ui.customizeui.CustomTextViewBold;
import com.mobileservice.autoreply.ui.customizeui.TopBar;
import com.mobileservice.autoreply.ui.model.PhoneContactModel;

public class BlockMessageActivity extends BaseActivity implements OnClickListener, OnEditorActionListener {

	private EditText searchingBox;
	private ListView listContact;
	private ContactItemAdapter adapter;
	private List<PhoneContactModel> phoneContactModels, templateContactModels;
	private PhoneContactManager contactManager;
	private ImageButton listButton, delete_text_btn;
	private CustomTextViewBold caption;
	private Loader loader;
	private TextView noContact;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms_block_layout);
		baseActivity = this;
		// Assign View for Layout
		AssignCaptionText();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (loader == null || loader.getStatus() != Status.RUNNING) {
			loader = new Loader();
			loader.execute();
		}
	}

	private void AssignCaptionText() {

		/** Create Manage for Phone */
		contactManager = PhoneContactManager.getInstance(getApplicationContext());
		/** Find View By ID */
		topBar = (TopBar) findViewById(R.id.topBar);
		searchingBox = (EditText) findViewById(R.id.searchingTb);
		listContact = (ListView) findViewById(R.id.listcontact);
		noContact = (TextView) findViewById(R.id.noContactText);

		caption = (CustomTextViewBold) topBar.findViewById(R.id.caption);
		listButton = (ImageButton) topBar.findViewById(R.id.list_setting_gear);
		delete_text_btn = (ImageButton) findViewById(R.id.delete_text);
		/** Setting Text View and active button */

		caption.setText("SMS Block");
		listButton.setVisibility(View.VISIBLE);
		delete_text_btn.setOnClickListener(this);
		searchingBox.setOnEditorActionListener(this);
		/** Set Adapter for List Contact View */
		phoneContactModels = new ArrayList<PhoneContactModel>();
		templateContactModels = new ArrayList<PhoneContactModel>();
		adapter = new ContactItemAdapter(baseActivity, R.layout.contact_item_apdater, phoneContactModels);

		searchingBox.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if (s != null && s.toString().length() > 0 && delete_text_btn.getVisibility() != View.VISIBLE) {
					delete_text_btn.setVisibility(View.VISIBLE);
				}
			}
		});
		listContact.setAdapter(adapter);
	}

	private class Loader extends BaseLoading {
		@Override
		protected Void doInBackground(Void... arg0) {

			if (phoneContactModels.size() > 0) {
				phoneContactModels.clear();
			}

			try {
				phoneContactModels.addAll(contactManager.getBlockPhoneSMSContactFollowByStatus(true));
				templateContactModels.clear();
				templateContactModels.addAll(phoneContactModels);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return super.doInBackground(arg0);
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (phoneContactModels != null && phoneContactModels.size() > 0) {
				noContact.setVisibility(View.GONE);
				listContact.setVisibility(View.VISIBLE);
				searchingBox.setEnabled(true);
			} else {
				noContact.setVisibility(View.VISIBLE);
				listContact.setVisibility(View.GONE);
				searchingBox.setEnabled(false);
			}
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onClick(View v) {
		int idVIew = v.getId();
		switch (idVIew) {
		case R.id.delete_text:
			searchingBox.setText("");
			delete_text_btn.setVisibility(View.INVISIBLE);
			break;
		}
	}

	/*
	 * Searching Contact Task
	 */
	private class SearchinAsyncTask extends BaseLoading {
		private String ContactName;

		public SearchinAsyncTask(String contactName) {
			this.ContactName = contactName;
		}

		@Override
		protected Void doInBackground(Void... arg0) {

			/** Searching Method */
			phoneContactModels.clear();
			for (PhoneContactModel contactModel : templateContactModels) {
				if ((contactModel.getContactName().toLowerCase().contains(ContactName) || contactModel.getContactNumber().toLowerCase().contains(ContactName))
						&& !phoneContactModels.contains(contactModel)) {
					phoneContactModels.add(contactModel);
				}
			}
			/** End */
			return super.doInBackground(arg0);
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub

			if (phoneContactModels != null && phoneContactModels.size() > 0) {
				noContact.setVisibility(View.GONE);
				listContact.setVisibility(View.VISIBLE);
				searchingBox.setEnabled(true);
			} else {
				noContact.setVisibility(View.VISIBLE);
				listContact.setVisibility(View.GONE);
				searchingBox.setEnabled(false);
			}
			adapter.notifyDataSetChanged();
			super.onPostExecute(result);
		}

	}

	@Override
	public boolean onEditorAction(TextView arg0, int actionId, KeyEvent arg2) {
		// TODO Auto-generated method stub
		if (actionId == EditorInfo.IME_ACTION_SEARCH) {
			String searchingText = arg0.getEditableText().toString();
			if (searchingText != null && searchingText.length() > 0) {
				new SearchinAsyncTask(searchingText).execute();
			} else if (templateContactModels.size() != phoneContactModels.size()) {
				phoneContactModels.clear();
				phoneContactModels.addAll(templateContactModels);
				adapter.notifyDataSetChanged();
			}
			return true;
		}
		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case CommConstant.ADD_CONTACT:
			if (resultCode == RESULT_OK) {

			}
			break;

		}
	}

	/** Save ing */
	public void Save() {
		new SaveContact().execute();
	}

	public class SaveContact extends BaseLoading {
		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			super.doInBackground(arg0);

			contactManager.UpdateOneFieldForListContact(PhoneContactTable.LOCK_SMS, adapter.SelectedModel);

			if (phoneContactModels.size() > 0) {
				phoneContactModels.clear();
			}

			try {
				phoneContactModels.addAll(contactManager.getBlockPhoneCallContactFollowByStatus(true));
				templateContactModels.clear();
				templateContactModels.addAll(phoneContactModels);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub+
			super.onPostExecute(result);
			if (phoneContactModels != null && phoneContactModels.size() > 0) {
				noContact.setVisibility(View.GONE);
				listContact.setVisibility(View.VISIBLE);
				searchingBox.setEnabled(true);
			} else {
				noContact.setVisibility(View.VISIBLE);
				listContact.setVisibility(View.GONE);
				searchingBox.setEnabled(false);
			}
			adapter.SelectedModel.clear();
			topBar.shiftButton(false);
			adapter.notifyDataSetChanged();
		}
	}

}
